package feng.demo.controller;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.http.useragent.UserAgent;
import com.fasterxml.jackson.databind.ObjectMapper;
import feng.demo.dao.LargefileDao;
import feng.demo.entity.*;
import feng.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/public")
public class PublicController {

//    设置验证请求

    @Autowired(required = false)
    UserService userService;
    @Autowired(required = false)
    LargefileDao largefileDao;
    @Autowired
    HotService hotService;
    @Autowired
    TypeService typeService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CommodityService commodityService;
    @Autowired
    RemarkService remarkService;
    @Autowired
    BreedService breedService;
    @Autowired
    PermService permService;
    @Autowired
    ObjectMapper objectMapper;
    @PostMapping("/login")
    public String login(@RequestParam String phone, @RequestParam String password,@RequestParam String captcha,HttpServletRequest request)throws  Exception{
        String string = request.getHeader("User-Agent");
        Object o = redisTemplate.opsForValue().get(string);
        String s = objectMapper.writeValueAsString(o);
        String result = s.replace("\"", "");
        if (!result.equals(captcha)){
            return SaResult.error("验证码错误").toString();
        }
        User user = userService.findByPhone(phone);
        if (user==null)return SaResult.error("没有该用户").toString();
        if (user.getClosed()==1)return SaResult.error("账号已被冻结").toString();
        String pwd = SaBase64Util.decode(user.getPassword());
        if (pwd.equals(password)){
            redisTemplate.opsForValue().set(""+user.getPhone(),user.getPerm().getVip(),7200, TimeUnit.SECONDS);
            StpUtil.login(user.getPhone());
            String token = StpUtil.getTokenValue();
            return SaResult.data(token).toString();
        }
        return SaResult.error("密码错误").toString();
    }
    @PostMapping("/login2")
    public String login2(@RequestParam String account, @RequestParam String password,@RequestParam String captcha,HttpServletRequest request)throws  Exception{
        String string = request.getHeader("User-Agent");
        Object o = redisTemplate.opsForValue().get(string);
        String s = objectMapper.writeValueAsString(o);
        String result = s.replace("\"", "");
        if (!result.equals(captcha)){
            return SaResult.error("验证码错误").toString();
        }
        User user = userService.findByAccount(account);
        if (user==null)return SaResult.error("没有该用户").toString();
        if (user.getClosed()!=0)return SaResult.error("账号已被冻结").toString();
        String pwd = SaBase64Util.decode(user.getPassword());
        if (pwd.equals(password)){
            redisTemplate.opsForValue().set(""+user.getPhone(),user.getPerm().getVip(),7200, TimeUnit.SECONDS);
            StpUtil.login(user.getPhone());
            String token = StpUtil.getTokenValue();
            return SaResult.data(token).toString();
        }
        return SaResult.error("密码错误").toString();
    }
    @GetMapping("/shows/{id}")
    public void Show(@PathVariable("id") Integer id, HttpServletResponse response ) throws Exception{//显示照片
        Largefile ones = largefileDao.findOne(id);
        Object content = ones.getContent();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        byte[] bytes=(byte[]) content;
        outputStream.write(bytes);
        outputStream.flush();
    }


    @GetMapping("/home")
    public SaResult home(){
//        首页获取类型跟推荐商品
        Map<String,Object> map=new HashMap<>();
        List<Hot> hots = hotService.findAll();
        List<Type> types = typeService.findAllLimit(0,14);
        List<Commodity> com = commodityService.findBySort(0, 6);
        map.put("type",types);
        map.put("hot",hots);
        map.put("com",com);
        return SaResult.data(map);
    }
    @GetMapping("/recom/{id}/{p}/{l}")
    public SaResult recom(@PathVariable("id")Integer typeid,@PathVariable("p")Integer pagenum,@PathVariable("l")Integer lines){
//        获取每次推荐商品
        if (typeid==0)typeid=null;
        Map<String,Object> map=new HashMap<>();
        Commodity commodity = new Commodity();
        commodity.getType().setTypeid(typeid);
        map.put("commodity",commodity);
        map.put("pagenum",pagenum);
        map.put("lines",lines);
        List<Commodity> list = commodityService.findByCommodity(map);
        return SaResult.data(list);
    }
    @GetMapping("/findBycom/{id}")
    public String fondBycom(@PathVariable("id")Integer comid){
//        商品详情
        Commodity com = commodityService.findById(comid);
        Map<String,Object> map=new HashMap<>();
        Commodity commodity = new Commodity();
        commodity.getType().setTypeid(com.getType().getTypeid());
        map.put("commodity",commodity);
        map.put("pagenum",0);
        map.put("lines",3);
        List<Commodity> list = commodityService.findByCommodity(map);
        Map<String,Object> m=new HashMap<>();
        Remark remark = new Remark();
        Commodity c = new Commodity();
        c.setComid(comid);
        remark.setCommodity(c);
        m.put("remark",remark);
        m.put("pagenum",0);
        m.put("lines",2);
        List<Remark> remarks = remarkService.findRemark(m);
        Map<String,Object>maps=new HashMap<>();
        maps.put("com",com);
        maps.put("list",list);
        maps.put("remark",remarks);
        return new XJson(200,"",maps).toString();
    }

    @GetMapping("/findRemark/{id}/{p}/{l}")
    public String findRemark(@PathVariable("id") Integer comid,@PathVariable("p")Integer p,@PathVariable("l")Integer l){
//        获取该商品评论信息
        System.out.println(comid);
        System.out.println(p);
        System.out.println(l);
        Map<String,Object> map=new HashMap<>();
        Commodity commodity = new Commodity();
        Remark remark = new Remark();
        remark.setCommodity(commodity);
        commodity.setComid(comid);
        map.put("remark",remark);
        map.put("pagenum",p);
        map.put("lines",l);
        List<Remark> remarks = remarkService.findRemark(map);
        return new XJson(200,"",remarks).toString();
    }

    @GetMapping("/findSearch/{p}/{l}")
    public String  findSearch(@PathVariable("p")Integer p,@PathVariable("l")Integer l){
//        获取查询时的数据
        int count ;
        List<Commodity> coms;
            count = commodityService.CountAll();
            coms = commodityService.findAllLimit(p,l);
        List<Breeds> breeds = breedService.findAlls();
        Map<String ,Object> maps=new HashMap<>();

        maps.put("breed",breeds);
        maps.put("com",coms);
        maps.put("count",count);
        return new XJson(200,"",maps).toString();
    }
    @GetMapping("/findSearchtTid/{p}/{l}/{id}")
    public String  findSearchTid(@PathVariable("p")Integer p,@PathVariable("l")Integer l,@PathVariable("id")Integer typeid){
//        获取查询时的数据
        int count ;
        List<Commodity> coms;
        count = commodityService.CountByTypeid(typeid);
        coms = commodityService.findByTypeidLimit(typeid,p,l);
        List<Breeds> breeds = breedService.findAlls();
        Map<String ,Object> maps=new HashMap<>();

        maps.put("breed",breeds);
        maps.put("com",coms);
        maps.put("count",count);
        return new XJson(200,"",maps).toString();
    }
    @GetMapping("/findAllPerm")
    public String findAllPerm(){
//        查询权限给注册选择商家还是用户
        List<Perm> list = permService.findAll();
        List<Perm> perms =new ArrayList<>();
        for (Perm p:list) {
            if (p.getPname().equals("商家")||p.getPname().equals("客户")){
                perms.add(p);
            }
        }
        return new XJson(200,"",perms).toString();
    }

    @PostMapping("/enroll")
    public String enroll(User user, Integer permid, MultipartFile img){
        user.getPerm().setPermid(permid);
        String pwd = SaBase64Util.decode(user.getPassword());
        user.setPassword(pwd);
        User user1 = userService.findByPhone(user.getPhone());
        User user2 = userService.findByAccount(user.getAccount());
        if (user1!=null){
            return  new XJson(401,"注册失败，手机号重复","").toString();
        }

        if (user2!=null){
            return  new XJson(401,"注册失败，账号重复","").toString();
        }
        if (img==null){
            userService.add(user);
        }else {
            Largefile largefile = new Largefile();
            try {
                largefile.setFilename(img.getOriginalFilename());
                byte[] bytes=img.getBytes();
                largefile.setContent(bytes);
            }catch (Exception e){

            }
            Integer integer = largefileDao.add(largefile);
            user.setPic(largefile.getId());
            userService.add(user);
        }
        return new XJson(200,"注册成功","").toString();

    }


    @PostMapping("/fgPwd")
    public  String fgPwd(User user){
        System.out.println(user);
        User u = userService.findBypwd(user);
        if (u==null)return new XJson(401,"查无此账号","").toString();
        String pwd = SaBase64Util.encode(user.getPassword());
        u.setPassword(pwd);
        userService.update(u);
        return new XJson(200,"修改成功","").toString();
    }

    @PostMapping("/select")
    public String select(String s){
        Map<String,Object> map=new HashMap<>();
        List<Commodity> list = commodityService.findByque(s);
        List<Breeds> breeds = breedService.findAlls();
        map.put("com",list);
        map.put("breed",breeds);
        return new XJson(200,"",map).toString();
    }




    @PostMapping("/a")
    public String a(@RequestParam(value = "pic",required = false)MultipartFile pic){
        Largefile largefile = new Largefile();
        try {
            largefile.setFilename(pic.getOriginalFilename());
            byte[] bytes=pic.getBytes();
            largefile.setContent(bytes);
        }catch (Exception e){

        }
        Integer integer = largefileDao.add(largefile);
        return new XJson(200,"",largefile.getId()).toString();
    }


// 图形验证
    @GetMapping("/captcha")
    public void  generateCaptcha(HttpServletResponse response, HttpServletRequest request) throws Exception{
//        设置前端显示大小
        String string = request.getHeader("User-Agent");
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(100, 40, 4, 40);
//验证码输出
        String code = circleCaptcha.getCode();//获取内容
        circleCaptcha.write(response.getOutputStream());//输出图片
        redisTemplate.opsForValue().set(string,code,7200, TimeUnit.SECONDS);
    }


 }
